package com.jiangyg.mall.core.support.validation.constraints;

import com.jiangyg.mall.core.support.validation.AbstractConstraintValidator;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 类描述：校验属性值是否为数字字母
 * 
 * @author jiangyg
 * @date 2020-08-02
 * @version 2.0
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = { Alphanumeric.AlphanumericConstraintValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
public @interface Alphanumeric {

    String message() default "{custom.validation.constraints.Alphanumeric.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 类描述：手机号码校验执行器
     * 
     * @author jiangyg
     * @date 2020-08-02
     * @version 2.0
     */
    class AlphanumericConstraintValidator extends AbstractConstraintValidator<Alphanumeric, String> {

        @Override
        public boolean execute(Alphanumeric a, String value, ConstraintValidatorContextImpl contextImpl) {
            // 非必填则可为空
            if (StringUtils.isBlank(value)) {
                return true;
            }
            // 匹配正则
            return Pattern.matches("[A-Za-z0-9]+", value);
        }

    }

}
